package ua.exchangeratesukraine.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.adapter.NbuAdapter;
import ua.exchangeratesukraine.model.CurrencyModel;
import ua.exchangeratesukraine.ui.activity.DBHelper;
import ua.exchangeratesukraine.util.Constants;
import ua.exchangeratesukraine.util.DataTask;
import ua.exchangeratesukraine.util.Util;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class FragmentNbu extends FragmentBase {

	private String	URL_NBU	= "";
	private List<String> currencyNamesList = null;
	private List<String> currencyCodesList = null;
	
	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
		
		View view = inflater.inflate(R.layout.fragment_nbu, null);

		listHeader = inflater.inflate(R.layout.list_header_nbu, null);
		listFooter = inflater.inflate(R.layout.list_footer, null);
		btnResult = (Button) view.findViewById(R.id.btnResult);
		tvDate = (TextView) view.findViewById(R.id.tvDate);
		tvCurrentDate = (TextView) view.findViewById(R.id.tvCurrentDate);
		bar = (ProgressBar) view.findViewById(R.id.progressBar);
		bar.setVisibility(View.INVISIBLE);
		btnResult.setOnClickListener(this);
		btnResult.setOnTouchListener(this);
		tvCurrentDate.setOnClickListener(this);
		tvCurrentDate.setOnTouchListener(this);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle inState) {
		date = getCurrentDate();
		if (inState != null) {
			date = inState.getString(Constants.DATE);
			isListShow = inState.getBoolean(Constants.IS_LIST_SHOW);
			currencyModelArray = inState.getParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY);

			if (isListShow) {
				setListHeader(listHeader);
				getListView().addFooterView(listFooter);
			}

			if (adapter == null) {
				adapter = getAdapter();
			}

			setListAdapter(adapter);
			fillTvDate(" " + getString(R.string.text_on_date) + " " + date);
		}
		fillTvCurrentDate(date);
		String[] currencyNames = getActivity().getResources().getStringArray(R.array.currency_names);
		String[] currencyCodes = getActivity().getResources().getStringArray(R.array.currency_codes);
		currencyNamesList = Arrays.asList(currencyNames);
		currencyCodesList = Arrays.asList(currencyCodes);
		Log.d(LOG_TAG, currencyCodes.length + " " + currencyNames.length);
		for (int i = 0; i < currencyCodes.length; i++) {
			currency.put(currencyCodes[i], currencyNames[i]);
		}
		super.onActivityCreated(inState);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.tvCurrentDate:
				showDateDialog();
				break;
			case R.id.btnResult:
				isNetworkAvailable = Util.isNetworkAvailable(context);
				if (!isNetworkAvailable) {
					showToast(getString(R.string.title_toast_connection_error),
							  getString(R.string.text_toast_connection_error));
					return;
				}
				boolean isTimeFuture = Util.isTimeFuture(date);
				if (isTimeFuture) {
					showToast(getString(R.string.title_toast_attention),
							  getString(R.string.text_day_no_present));
					return;
				}
				boolean isDayOff = Util.isDayOff(holidayMonthArray, holidayDayArray, date);
				if (isDayOff) {

					showToast(getString(R.string.title_toast_attention), getString(R.string.text_day_off));
					return;
				}
//				checkFieldDB();
				toServer();
				break;
			default:
				break;
		}
	}

	boolean isDataPresent = false;
	
	@Override
	public void setDataFromDB() {
		if (!isListShow) {
			setListAdapter(null);
			setListHeader(listHeader);
			getListView().addFooterView(listFooter);
		}
		setCurrencyName(currencyModelArray); // for NBU
		if (!Locale.getDefault().toString().equals("ru_RU"))
			setBanksName(currencyModelArray); // for Banks

		sort((TextView) getActivity().findViewById(R.id.tvNameCurrencyUnit), false);
		initArray(currencyModelArray);
	}

	public void checkFieldDB(){
		Log.d(LOG_TAG, "****** checkFieldDB *******");
		dbHelper = new DBHelper(context);
		cv = new ContentValues();
		db = dbHelper.getWritableDatabase();
		// check DB data by date

		String query = "SELECT * FROM '" + currencyCodesList.get(0) + "'" 
				+ " WHERE date '" + date + "'";
		
		Cursor c = db.rawQuery(query, null);
		if(c == null) toServer(); //writeDataToDB();
		else readFromDataDB(c);
	}

	public void toServer() {
		Log.d(LOG_TAG, "****** toServer *******");
			URL_NBU = BASE_URL + "/kursy-valut/nbu_xml/?id=" + WEB_ID + "&date=" + date;
			Log.d(LOG_TAG, "Date on click : " + date);
			Log.d(LOG_TAG, "URL_NBU : " + URL_NBU);
			fillTvCurrentDate(date);
			
			DataTask mTask = new DataTask(context, this);
			mTask.execute(URL_NBU);
	}
	
	private void readFromDataDB(Cursor c){
		Log.d(LOG_TAG, "****** readFromDataDB *******");
		
//		db = dbHelper.getWritableDatabase();
		
		for (String currencyCode : currencyCodesList) {
			
			String query = "SELECT * FROM " + currencyCode 
					+ " WHERE date " + "'" + date + "'";
			c = db.rawQuery(query, null);
			
		// set cursor to first line of selection
	      // if not lines, return false
	      if (c.moveToFirst()) {
	        // Specifies the columns number by name
	    	int idColIndex = c.getColumnIndex("id");
			int nameColIndex = c.getColumnIndex("name");
			int codeColIndex = c.getColumnIndex("code");
			int dateColIndex = c.getColumnIndex("year");
			int rateColIndex = c.getColumnIndex("rate");
			int absColIndex = c.getColumnIndex("abs");
			int relColIndex = c.getColumnIndex("rel");

	        do {
	          // gets the columns number
	          Log.d(LOG_TAG,
	              "ID = " + c.getInt(idColIndex) + 
	              ", name = " + c.getString(nameColIndex) +
	              ", code = " + c.getString(codeColIndex) +
	              ", date = " + c.getString(dateColIndex) +
	              ", rate = " + c.getFloat(rateColIndex) +
	              ", abs = " + c.getFloat(absColIndex) +
	              ", rel = " + c.getFloat(relColIndex));
	          // to the next line 
	          // if there is no next line (current - last), the false - exit the loop
	          if((c.getString(dateColIndex)).equals(date)){
	        	  
	        	  CurrencyModel unit = new CurrencyModel();
	        	  unit.setName(c.getString(nameColIndex));
	        	  unit.setCode(c.getString(codeColIndex));
	        	  unit.setChangeAbs((String.valueOf(c.getFloat(absColIndex))));
	        	  unit.setChangeRel((String.valueOf(c.getFloat(relColIndex))));
	        	  unit.setRate(String.valueOf(c.getFloat(rateColIndex)));
	        	  unit.setDate(c.getString(dateColIndex));
	        	  currencyModelArray.add(unit);
	          }
	        	  
	        	  
	        } while (c.moveToNext());
	      } else {
	    	  Log.d(LOG_TAG, "0 rows");
	      }
	      c.close();
		}
      dbHelper.close();
	  }

	@Override
	protected void writeDataToDB() {
//		protected void fillDB(SQLiteDatabase db, ContentValues cv) {
		
		Log.d(LOG_TAG, "******* writeDataToDB Start *******");
		db = dbHelper.getWritableDatabase();
		for (String currencyCode : currencyCodesList) {
			
			Log.d(LOG_TAG, "currencyCode = " + currencyCode);
		}
		for (CurrencyModel currencyModel : currencyModelArray) {
		Cursor c = db.query(currencyModel.getCode(), null, null, null, null, null, null);
		 // set cursor to first line of selection
	      // if not lines, return false
		String dateDB = "";
	      if (c.moveToFirst()) {
	        // Specifies the columns number by name
	    	int idColIndex = c.getColumnIndex("id");
			int nameColIndex = c.getColumnIndex("name");
			int codeColIndex = c.getColumnIndex("code");
			int dateColIndex = c.getColumnIndex("date");
			int rateColIndex = c.getColumnIndex("rate");
			int absColIndex = c.getColumnIndex("abs");
			int relColIndex = c.getColumnIndex("rel");

	        do {
	          // gets the columns number
	          Log.d(LOG_TAG,
	              "ID = " + c.getInt(idColIndex) + 
	              ", name = " + c.getString(nameColIndex) +
	              ", code = " + c.getString(codeColIndex) +
	              ", date = " + c.getString(dateColIndex) +
	              ", rate = " + c.getFloat(rateColIndex) +
	              ", abs = " + c.getFloat(absColIndex) +
	              ", rel = " + c.getFloat(relColIndex));
	          // to the next line 
	          // if there is no next line (current - last), the false - exit the loop
	          dateDB = c.getString(dateColIndex);
	        } while (c.moveToNext());
	      } else {
	    	  Log.d(LOG_TAG, "dateDB = " + dateDB + "; date = " + date);
	      }
	      
	      Log.d(LOG_TAG, "");
	      if(!dateDB.equalsIgnoreCase(date)){
	    	  
	      	cv.put("name", currencyModel.getName());
	      	cv.put("code", currencyModel.getCode());
			cv.put("date", currencyModel.getDate());
			cv.put("rate", Float.valueOf(currencyModel.getRate()));
			cv.put("abs", Float.valueOf(currencyModel.getChangeAbs()));
			cv.put("rel", Float.valueOf(currencyModel.getChangeRel()));
			long rowID = db.insert(currencyModel.getCode(), null, cv);
			Log.d(LOG_TAG, "Table Name = " + currencyModel.getCode() + "; rowID = " + rowID);
	      }
			c.close();
		}
	    dbHelper.close();

	    Log.d(LOG_TAG, "******* writeDataToDB End *******");
	}
	
	
	protected NbuAdapter getAdapter() {
		
		return new NbuAdapter(context, currencyModelArray);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {

		outState.putBoolean(Constants.IS_LIST_SHOW, isListShow);
		outState.putString(Constants.DATE, date);
		outState.putParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY, currencyModelArray);

		super.onSaveInstanceState(outState);
	}
	
	public void sort(final View view, boolean isRequest) {
		Log.d(LOG_TAG, "Locale = " + Locale.getDefault());
		if (!currencyModelArray.isEmpty() && view != null) {
			if (isRequest) {
				touchUnitCount = 0;
				touchChangeCount = 0;
				touchAbsCount = 0;
				touchRelCount = 0;
			}
			switch (view.getId()) {
			case R.id.tvNameCurrencyUnit: 	touchUnitCount++; 		break;
			case R.id.tvRate:  				touchChangeCount++;	 	break;
			case R.id.tvNameChangeAbsRate:  touchAbsCount++;		break;
			case R.id.tvNameChangeRelRate:	touchRelCount++;		break;
			default:												break;
			}
			if (Locale.getDefault().toString().equals("uk_UA")) {
				for (CurrencyModel currencyModel : currencyModelArray) {
					char[] name = currencyModel.getName().toCharArray();
					if (name[0] == Constants.SYMBOL_UKR_E ){
						name[0] = Constants.SYMBOL_RUS_E;
						currencyModel.setName(String.valueOf(name));
					}
					if (name[0] == Constants.SYMBOL_UKR_I ){
						name[0] = Constants.SYMBOL_RUS_I;
						currencyModel.setName(String.valueOf(name));
					}
				}
			}
			Collections.sort(currencyModelArray, new Comparator<CurrencyModel>() {
				public int compare(CurrencyModel s1, CurrencyModel s2) {
					switch (view.getId()) {
						case R.id.tvNameCurrencyUnit:
							if(touchUnitCount % 2 == 0)   return s2.getName().compareTo(s1.getName());
							else 					   	  return s1.getName().compareTo(s2.getName()); 
						case R.id.tvRate:
							if(touchChangeCount % 2 == 0) return (Double.valueOf(s2.getRate()).compareTo(
																  Double.valueOf(s1.getRate()))); 
							else 						  return (Double.valueOf(s1.getRate()).compareTo
									  							 (Double.valueOf(s2.getRate()))); 
						case R.id.tvNameChangeAbsRate:
							if(touchAbsCount % 2 == 0) 	  return  Double.valueOf(s2.getChangeAbs()).compareTo
									 							 (Double.valueOf(s1.getChangeAbs()));
							else 						  return  Double.valueOf(s1.getChangeAbs()).compareTo
		 														 (Double.valueOf(s2.getChangeAbs()));
						case R.id.tvNameChangeRelRate:
							if(touchRelCount % 2 == 0)    return  Double.valueOf(s2.getChangeRel()).compareTo
															 	 (Double.valueOf(s1.getChangeRel()));
							else 						  return  Double.valueOf(s1.getChangeRel()).compareTo
									 							 (Double.valueOf(s2.getChangeRel()));
						default:break;
					}
					return 0;
				}
			});
			if (Locale.getDefault().toString().equals("uk_UA")) {
				for (CurrencyModel currencyModel : currencyModelArray) {
					char[] name = currencyModel.getName().toCharArray();
					if (name[0] == Constants.SYMBOL_RUS_E ){
						name[0] = Constants.SYMBOL_UKR_E;
						currencyModel.setName(String.valueOf(name));
					}
					if (name[0] == Constants.SYMBOL_RUS_I ){
						name[0] = Constants.SYMBOL_UKR_I;
						currencyModel.setName(String.valueOf(name));
					}
				}
			}
		}
		initArray(currencyModelArray);
	}

	@Override
	protected void setCurrencyName(ArrayList<CurrencyModel> currencyModelArray) {
		for (CurrencyModel currencyModel : currencyModelArray) {
			for (Entry<String, String> cur : currency.entrySet()) {
				if(currencyModel.getCode().equals(cur.getKey()))
					currencyModel.setName(cur.getValue());
			}
		}

	}

}